#include "linux_tcp.h"
// Linux Socket编程接口
#include <sys/socket.h>
// Socket ipv4地址结构接口
#include <netinet/in.h>
// Linux 文件IO接口
#include <unistd.h>
// C库
#include <stdio.h>



int LinuxUdpServer(unsigned short port)
{
    char recv_buf[64] = "";
    char send_buf[64] = "Udp Server Over";
    struct sockaddr_in cient_addr = {0};

    /* 创建socket */
    int sock_fd = socket(AF_INET, SOCK_DGRAM, 0);
    if (sock_fd < 0) {
        printf("[ERROR] socket fail\n");
        return -1;
    }
    printf("[INFO] socket success\n");

    /* 定义地址结构 */
    struct sockaddr_in server_addr = {
        .sin_port = htons(port),
        .sin_family = AF_INET,
        .sin_addr.s_addr = htonl(INADDR_ANY),
    };

    /* 绑定IP、端口 */
    if (bind(sock_fd, (struct sockaddr *)&server_addr, sizeof(server_addr)) < 0) {
        printf("[ERROR] bind fail\n");
        return -1;
    }
    printf("[INFO] bind success\n");

    /* 接收客户端发送的数据 */
    socklen_t clientAddrLen = sizeof(cient_addr);
    int recv_bytes = recvfrom(sock_fd, recv_buf, sizeof(recv_buf), 0, (struct sockaddr *)&cient_addr, &clientAddrLen);
    if (recv_bytes < 0) {
        printf("[ERROR] recvfrom fail\n");
        return -1;
        
    }
    printf("[INFO] recv success %d bytes\n", recv_bytes);
    printf("%s\n", recv_buf);

    /* 使用recvfrom获取的来源地址，返回给对方一个消息 */
    if (recv_bytes > 8) {
        if (sendto(sock_fd, send_buf, sizeof(send_buf), 0, (struct sockaddr *)&cient_addr, clientAddrLen) <0 ) {
            printf("[ERROR] sendto fail\n");
            return -1;
        }
        printf("[INFO] sendto success\n");
    }
    

    // 关闭文件
    close(sock_fd);
    return 0;
}
